package com.chaoyer.cynet.controller;

import com.alibaba.fastjson.JSONObject;
import com.chaoyer.cynet.cache.GhostPostCache;
import com.chaoyer.cynet.cache.domain.GhostPost;
import com.chaoyer.cynet.common.annotation.Get;
import com.chaoyer.cynet.common.annotation.Post;
import com.chaoyer.cynet.common.context.CyNetContext;
import com.chaoyer.cynet.common.domain.WebResult;
import com.chaoyer.cynet.common.exception.ValidateException;
import com.chaoyer.cynet.entity.PostPv;
import com.chaoyer.cynet.service.PostPvService;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by lwc.
 * Description:
 * Date: 2018-05-20
 * Time: 下午4:47
 */
@Controller
public class GhostPostController {

    @Resource
    private PostPvService postPvService;
    @Resource
    private GhostPostCache ghostPostCache;

    /*
     * 获取文章的阅读数
     * */
    @Get("/pv")
    public WebResult<PostPv> getMyPostPv(CyNetContext ctx) throws ValidateException {
        String postId = ctx.queryParam("postId").toString();
        return WebResult.success(postPvService.getPvByPostId(postId));
    }

    /*
     *  更新文章的阅读数
     * */
    @Post("/pv")
    public WebResult<PostPv> updateMyPostPv(CyNetContext ctx) throws ValidateException {
        String postId = ctx.bodyParam("postId").toString();
        postPvService.addPvByPostId(postId);
        return WebResult.success(postPvService.getPvByPostId(postId));
    }

    /*
     * 搜索文章
     * */
    @Get("/ghost/post/search")
    public WebResult<List<GhostPost>> search(CyNetContext ctx) {
        String name = ctx.queryParam("search").toString();
        return WebResult.success(postPvService.searchByPostName(name));
    }

    /*
     * ghost网站详情
     * */
    @Get("/ghost/info")
    public WebResult<JSONObject> getGhostInfo(CyNetContext ctx) {
        JSONObject r = new JSONObject();
        r.put("post_total", ghostPostCache.getBLOG_TOTAL_NUM());
        r.put("tag_total", ghostPostCache.getTAG_TOTAL_NUM());
        return WebResult.success(r);
    }

    /*
     * ghost网站缓存更新
     * */
    @Post("/ghost/info/refresh")
    public WebResult<Boolean> refresh(CyNetContext ctx) {
        ghostPostCache.init();
        return WebResult.success(true);
    }

}
